<template>
  <div class="user-center">
    <div class="content">
      <div class="assets">
        <div class="user">
          <div class="avatar">
            <!-- <img src="../../assets/images/2.png" /> -->
            <img :src="avatar" :onerror="errorImg" />
          </div>
          <div class="info">
            <div>{{nickname}}</div>
            <div class="m-t-12">{{phone}}</div>
          </div>
        </div>
        <div class="assets-item">
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">万能账户</div>
            <div class="assets-item__panel__num">{{commission}}</div>
          </div>
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">元宝</div>
            <div class="assets-item__panel__num">{{balance}}</div>
          </div>
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">钻石</div>
            <div class="assets-item__panel__num">{{jewelry}}</div>
          </div>
        </div>
        <div class="assets-item">
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">天使股</div>
            <div class="assets-item__panel__num">{{classAngel}}</div>
          </div>
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">BCL锁仓</div>
            <div class="assets-item__panel__num">{{lockBcl}}</div>
          </div>
          <div class="assets-item__panel">
            <div class="assets-item__panel__text">BCL释放总数</div>
            <div class="assets-item__panel__num">{{bcl}}</div>
          </div>
        </div>
      </div>
      <div class="order-panel">
        <div class="order-panel__header">
          <div class="title">我的订单</div>
          <div class="all" @click="handleOrder(-1)">全部订单＞</div>
        </div>
        <div class="order-panel__list">
          <div class="order-panel__list__item" @click="handleOrder(0)">
            <i class="unpay"></i>
            <div>未付款</div>
          </div>
          <div class="order-panel__list__item" @click="handleOrder(201)">
            <i class="unsend"></i>
            <div>待发货</div>
          </div>
          <div class="order-panel__list__item" @click="handleOrder(300)">
            <i class="unreceive"></i>
            <div>待收货</div>
          </div>
          <div class="order-panel__list__item" @click="handleOrder(301)">
            <i class="receive"></i>
            <div>已收货</div>
          </div>
        </div>
      </div>

      <ul class="action-list">
        <!-- <li class="action-list-item" @click="handleOrder">
          <div class="action-list-item__left" >
            <i class="i-list"></i>
            <div  class="m-l-8">我的订单</div>
          </div>
          <i class="i-right"></i>
        </li> -->
        <!-- <li class="action-list-item">
          <div class="action-list-item__left">
            <i class="i-phone"></i>
            <div  class="m-l-8">绑定手机</div>
          </div>
          <i class="i-right"></i>
        </li> -->
        <li class="action-list-item" @click="handleSharing">
          <div class="action-list-item__left">
            <i class="i-earn"></i>
            <div class="m-l-8">分享赚钱</div>
          </div>
          <i class="i-right"></i>
        </li>
        <li class="action-list-item" @click="handleInvite">
          <div class="action-list-item__left">
            <i class="i-record"></i>
            <div class="m-l-8">邀请记录</div>
          </div>
          <i class="i-right"></i>
        </li>
        <li class="action-list-item" @click="handleAddress"> 
          <div class="action-list-item__left">
            <i class="i-address"></i>
            <div class="m-l-8">收货地址</div>
          </div>
          <i class="i-right"></i>
        </li>
      </ul>
      <!-- <div class="action">
        <div class="action-panel" @click="handleOrder">
          <i class="i-order"></i>
          <div class="action-panel__num">我的订单</div>
        </div>
        <div class="action-panel" @click="handleAddress">
          <i class="i-addr"></i>
          <div class="action-panel__num">我的地址</div>
        </div>
      </div> -->
      <footerbar></footerbar>
    </div>
    <div class="show-box" v-if="showBox">
      <div class="binding">
        <div class="binding-header">
          <div class="space"></div>
          <div class="title">绑定手机</div>
          <div class="space"></div>
          <!-- <i class="i-close" @click="handleClose"></i> -->
        </div>
        <div class="form">
          <div class="form-item">
              <i class="i-b-phone"></i>
              <input type="number" v-model="form.telephone" class="inpt" placeholder="请填写您的手机号码" @focus="handleFocus('telephone')" />
          </div>
          <div class="err-message" v-if="errorMsg.telephone">{{errorMsg.telephone}}</div>
          <div class="form-item">
            <div class="form-item__left">
              <i class="i-b-code"></i>
              <input type="number" v-model="form.randcode"  class="inpt h-p-80" placeholder="请输入手机验证码" @focus="handleFocus('randcode')" />
            </div>
           <button v-show="show" class="btn-send" :disabeld="btnDisabld" @click="handleSendMessage">获取验证码</button>
           <button v-show="!show" v-if="count>=10" class="btn-send">{{count}} s</button>
           <button v-show="!show" v-else-if="count<10" class="btn-send">0{{count}} s</button>
          </div>
          <div class="err-message" v-if="errorMsg.randcode">{{errorMsg.randcode}}</div>
          <div class="form-item">
              <i class="i-b-msg"></i>
              <input type="text" v-model="form.recommendCode" class="inpt" placeholder="请填写用户邀请码" />
          </div>
          <div class="err-message" v-if="errorMsg.recommendCode">{{errorMsg.recommendCode}}</div>
          <div class="tips">已注册用户无需填写邀请码</div>
          <button class="btn-binding" @click="handleBinding">确定</button>
        </div>
      </div>
      <div></div>
  </div>
  <div class="show-box-overlay" v-if="showBox"></div>
  </div>
</template>

<script>
import footerbar from "@/components/footerbar"    
import { Dialog } from 'vant'  
import validator from '@/utils/validator'
import {  getUserInfo, getUserMoney,getCode, userBinding } from "@/api/bdchats"

export default {
  components: {footerbar},
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validateMobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    };
    return {
      unRegister: false,
      show: true,
      timer: null,
      count: 0,
      second: 60,
      btnDisabld: false,
      showBox: false,
      openid: '',
      avatar: '',
      errorImg: 'this.src="https://images.bdchats.com/prod/upload/default-user.png"',
      nickname: '',
      phone: '',
      commission: 0,
      jewelry: 0,
      balance: 0,
      classAngel: 0,
      bcl: 0,
      lockBcl: 0,
      reg: /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/,
      form: {
        telephone: '',
        randcode: '',
        recommendCode: ''
      },
      rules: {
        telephone:[{validator: validatePhone, message: '请输入正确的手机号码'}],
        randcode: [{required: true, message: '请输入手机验证码'}]
      },
      errorMsg: {
        telephone: '',
        randcode: '',
        recommendCode: ''
      }
    };
  },
  created() {
    // localStorage.clear()
    let userid = 0
    let access_token = ''
    if(this.$route.query) {
      if(this.$route.query.recommendCode && this.$route.query.recommendCode!="undefined") {
        this.form.recommendCode = this.$route.query.recommendCode
        this.disabled = true
      }
     
      this.openid = this.$route.query.openid
      if(this.openid ) {
        if(this.openid) {
          // localStorage.setItem('openid',this.$route.query.openid)
          this.$cookies.set("openid",this.$route.query.openid,60 * 60 * 24 * 7) //有效期7天
        }
      }
      userid = this.$route.query.userId
      if(userid) {
        // localStorage.setItem('userId', userid)
        this.$cookies.set("userId",userid, 60 * 60 * 24 * 7) //有效期7天
      }
      access_token = this.$route.query.access_token
      if(access_token) {
        // localStorage.setItem('token', access_token)
        this.$cookies.set("token",access_token,60 * 60 * 24 * 7) //有效期7天
      }
      if(userid && access_token) {
        const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
        // localStorage.setItem('expires_in', parseInt(expiresIn/1000) )
        this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 
      }
    }
    let url = process.env.VUE_APP_BDCHATS_API + '/weixin/auth/login?webCallBack=' + window.location.protocol + '//' + window.location.host  + '/user/center'
    if(!this.$cookies.get('openid') || this.$cookies.get('openid')==='undefined' || this.$cookies.get('openid')===undefined) { 
      window.location.href = url
    } else {
      if(this.$cookies.get('userId') === undefined || this.$cookies.get('userId')=== 'undefined') {
        window.location.href = url
      }
      if(this.$cookies.get('token') === undefined || this.$cookies.get('token')=== 'undefined') {
        window.location.href = url
      }
    }
    // console.log(window.location.href)
    // alert( window.location.href)
    // alert(localStorage.getItem('openid'))
    // alert(localStorage.getItem('userId'))
    // alert(localStorage.getItem('token'))

    
    if(this.$cookies.get('openid') && this.$cookies.get('openid') !== 'undefined'){
      if(!this.$cookies.get('userId') || !this.$cookies.get('token')){
        if(userid && access_token && userid != "0" && access_token !='' && userid != 0 && !localStorage.getItem('expires_in')) {
          // localStorage.setItem('userId', userid)
          // localStorage.setItem('token', access_token)
          const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
          // localStorage.setItem('expires_in', parseInt(expiresIn/1000) )


          this.$cookies.set("userId", userid, 60 * 60 * 24 * 7) 
          this.$cookies.set("token", access_token, 60 * 60 * 24 * 7) 
          this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 
          this.isBinding()
        } else {
          this.showBox = true
        }
      }
    } else {
      window.location.href = url
    }
    if(this.$cookies.get('userId') && this.$cookies.get('token')  
    && this.$cookies.get('userId') != undefined && this.$cookies.get('userId') != 'undefined'
    && this.$cookies.get('token') != undefined && this.$cookies.get('token') != 'undefined'
    &&this.$cookies.get('userId') !== 0) {
      this.getUser()
      this.getAssets();
    }
    this.validator = validator(this.rules, this.form);
    this.$store.commit('SET_ACTIVE', 2)
  },
  methods: {
    handleClose() {
      this.showBox = false
    },
    handleFocus(type) {
      if(type === "telephone") {
        this.errorMsg.telephone = ""
      } else if(type === "randcode") {
        this.errorMsg.randcode = ""
      }
    },
    getUser() {
      getUserInfo().then(response=>{
        if(response.data) { 
          this.avatar = process.env.VUE_APP_AVATAR_URL + (response.data.userId % 10000) + '/' + response.data.userId + '.jpg'
          this.phone = response.data.phone
          this.nickname = response.data.nickname
        }

      })
    },
    getAssets() {
      getUserMoney().then(response=>{
        if(response.data) {
          this.commission = Math.floor(response.data.commission * 100) / 100 
          this.balance =  Math.floor(response.data.balance * 100) / 100 
          this.jewelry = response.data.jewels 
          this.classAngel = response.data.classAngel
          this.bcl = Math.floor(response.data.bcl  * 100) / 100 
          this.lockBcl = Math.floor(response.data.lockedBcl * 100) / 100 
        }
      })
    },
    handleReturn() {
      this.$router.go(-1);
    },
    imageShow(src) {
      const img = {};
      img.loading = require("@/assets/images/loading.gif");
      img.src = src;
      return img;
    },
    getUserInfo() {},
    handleOrder(status) {
      if(status !==-1) {
        sessionStorage.setItem('orderStatus', status)
      } else {
        sessionStorage.setItem('orderStatus', '')
      }
      this.$router.push("/user/orderlist")
    },
    handleAddress() {
      this.$router.push("/address/list");
    },
    handleSharing() {
      this.$router.push("/user/sharing");
    },
    isBinding() {
      getUserInfo().then(response=>{
        if(!response.data.openid) { 
          this.showBox = true
        }
      })
    },
    handleSendMessage() {
      this.btnDisabld = true
      if (!this.reg.test(this.form.telephone) || !this.form.telephone) {
        this.errorMsg.telephone = '请输入正确的手机号码'
        return
      }
      const data = {}
      data.areaCode = 86
      data.telephone = this.form.telephone
      data.isRegister = 2
      getCode(data).then(response => {
        this.btnDisabld = false
        if (response && response.resultCode && response.resultCode === 1) {
          if (!this.timer) {
            this.count = this.second
            this.show = false
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= this.second) {
                this.count--
              } else {
                this.show = true
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        }
      })
      
    },
    handleBinding() {
      const self = this
      this.validate((errors, fields) => {
        let flag = false
        if (!this.reg.test(this.form.telephone) || !this.form.telephone) {
            this.errorMsg.telephone = '请输入正确的手机号码'
            flag = true
        }
        if (errors === false) {
          if(flag) {
            return
          }
          const data = {}
          data.areaCode = 86
          data.telephone = this.form.telephone
          data.randcode = this.form.randcode
          data.recommendCode = this.form.recommendCode
          data.openid = this.openid ? this.openid : localStorage.getItem('openid')  
          userBinding(data).then(response =>{
            if(response.resultCode===1) {
              Dialog.alert({
                title: "",
                message:  response.resultMsg
              }).then(() => {
                this.showBox = false
                const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
                this.$cookies.set("userId", response.data.userId, 60 * 60 * 24 * 7) 
                this.$cookies.set("token", response.data.access_token, 60 * 60 * 24 * 7) 
                this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 
              })
            } else {
              Dialog.alert({
                title: "",
                message: response.resultMsg
              }).then(()=> {
                // this.showBox = false
              })
            }
          });
        }
      })
    },
    handleInvite() {
      this.$router.push("/invite/record")
    },
    /**
      * 清除验证提示
      * @param attrs
    */
    resetField(attrs) {
      attrs = !attrs ? Object.keys(this.errorMsg) : ( Array.isArray(attrs) ? attrs : [attrs]);
      attrs.forEach(attr => {
        this.errorMsg[attr] = ''
      })
    },
    /**
      * 验证方法
      * @param callback
      * @param data
    */
    validate(callback, data) {
      const self = this
      this.validator.validate((errors, fields) => {
        this.resetField();
        if (errors) {
          fields.forEach(item => {
            self.errorMsg[item.field] = item.message
          })
        }
        callback && callback(errors, fields)
      }, data);
    }
  }
};
</script>
